package com.qx.chat.websocket.handler;

import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.BinaryWebSocketHandler;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import com.qx.chat.akka.Qxchat;
import com.qx.chat.system.event.SessionEvent;
import com.qx.chat.system.message.Data;
import com.qx.chat.system.util.JsonUtil;

import akka.actor.ActorRef;
 
/**
 * 功能说明：WebSocket处理器
 * 可以继承 {@link TextWebSocketHandler}/{@link BinaryWebSocketHandler}，
 * 或者简单的实现{@link WebSocketHandler}接口
 * 作者：cyf(2016-01-25 03:42)
 */
public class QxWebSocketHandler extends TextWebSocketHandler {
 
    private static final Logger LOGGER = LoggerFactory.getLogger(QxWebSocketHandler.class);
 
    /**
     * 建立连接
     * @param session
     * @throws Exception
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        String loginName = MapUtils.getString(session.getAttributes(), "loginName");
        ActorRef sessionActor = Qxchat.getInstance().getSessionActor();
		sessionActor.tell(
				new SessionEvent.SessionOpen(loginName, session),
				sessionActor);
    }
 
    /**
     * 收到客户端消息
     * @param session
     * @param message
     * @throws Exception
     */
    @Override
    public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
    	String loginName = MapUtils.getString(session.getAttributes(), "loginName");
        ActorRef userActor = Qxchat.getInstance().getActorByLoginName(loginName);
        Data<?> data = JsonUtil.fromJson(message.getPayload().toString(), Data.class);
		userActor.tell(data, userActor);
    }
 
    /**
     * 出现异常
     * @param session
     * @param exception
     * @throws Exception
     */
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        String loginName = MapUtils.getString(session.getAttributes(), "loginName");
        ActorRef sessionActor = Qxchat.getInstance().getSessionActor();
		sessionActor.tell(
				new SessionEvent.SessionError(loginName, session),
				sessionActor);
        LOGGER.error("websocket connection exception: " + loginName);
        LOGGER.error(exception.getMessage(), exception);
    }
 
    /**
     * 连接关闭
     * @param session
     * @param closeStatus
     * @throws Exception
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
    	String loginName = MapUtils.getString(session.getAttributes(), "loginName");
        ActorRef sessionActor = Qxchat.getInstance().getSessionActor();
		sessionActor.tell(
				new SessionEvent.SessionClose(loginName, session),
				sessionActor);
		LOGGER.info(loginName+" logout");
    }
 
    /**
     * 是否分段发送消息
     * @return
     */
    @Override
    public boolean supportsPartialMessages() {
        return false;
    }
 
}